'use client'

import React, { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Slider } from '@/components/ui/slider'
import { api } from '@/lib/api'
import { 
  Upload, 
  PlayCircle, 
  CheckCircle, 
  Clock, 
  Download,
  Eye,
  Settings,
  Layers,
  Zap,
  Globe,
  Cpu,
  Palette
} from 'lucide-react'

interface UnifiedStrategy {
  unified_approach: {
    name: string
    version: string
    description: string
    philosophy: string
  }
  integrated_technologies: Array<{
    name: string
    display_name: string
    role: string
    description: string
    advantages: string[]
  }>
  processing_pipeline: {
    intelligent_fusion: boolean
    stages: Array<{
      order: number
      name: string
      technologies: string[]
      output: string
    }>
  }
  output_capabilities: {
    formats: string[]
    quality_levels: string[]
    interactive_features: string[]
    platform_support: string[]
  }
  user_benefits: {
    no_technical_decisions: string
    guaranteed_quality: string
    comprehensive_output: string
    future_proof: string
  }
  customization_options: {
    quality_priority: string
    output_preference: string
    feature_toggles: string
    platform_optimization: string
  }
}

const UnifiedModelingPage = () => {
  const [selectedFile, setSelectedFile] = useState<File | null>(null)
  const [uploadedFileId, setUploadedFileId] = useState<string>('')
  const [analysisResult, setAnalysisResult] = useState<any>(null)
  const [modelingStatus, setModelingStatus] = useState<string>('idle')
  const [modelId, setModelId] = useState<string>('')
  const [finalResult, setFinalResult] = useState<any>(null)
  const [strategies, setStrategies] = useState<UnifiedStrategy | null>(null)
  const [progress, setProgress] = useState(0)

  // 用户偏好设置
  const [qualityPriority, setQualityPriority] = useState([80])
  const [speedPriority, setSpeedPriority] = useState([60])
  const [webCompatibility, setWebCompatibility] = useState(true)
  const [professionalGrade, setProfessionalGrade] = useState(false)

  // 加载统一策略信息
  useEffect(() => {
    const fetchStrategies = async () => {
      try {
        const result = await api.unifiedModeling.getStrategies()
        console.log('策略数据:', result) // 调试用
        setStrategies(result)
      } catch (error) {
        console.error('获取统一策略失败:', error)
      }
    }
    fetchStrategies()
  }, [])

  // 文件上传处理
  const handleFileUpload = async () => {
    if (!selectedFile) return

    try {
      // 直接传递selectedFile，api.floor.upload内部会处理FormData
      const uploadResult = await api.floor.upload(selectedFile)
      setUploadedFileId(uploadResult.fileId)
      
      // 自动开始异步分析
      const analysisTask = await api.unifiedModeling.analyze(uploadResult.fileId)
      
      if (analysisTask.task_id) {
        // 开始轮询分析状态
        pollAnalysisStatus(analysisTask.task_id)
      } else {
        // 如果返回的是直接结果（向后兼容）
        setAnalysisResult(analysisTask)
      }
      
    } catch (error) {
      console.error('文件上传失败:', error)
    }
  }

  // 开始统一建模
  const startUnifiedModeling = async () => {
    if (!uploadedFileId) return

    try {
      setModelingStatus('processing')
      setProgress(0)

      const buildParams = {
        file_id: uploadedFileId,
        quality_priority: qualityPriority[0] / 100,
        speed_priority: speedPriority[0] / 100,
        web_compatibility: webCompatibility,
        professional_grade: professionalGrade,
        output_formats: ['glb', 'web_demo', 'amap_integration']
      }

      const result = await api.unifiedModeling.build(buildParams)
      setModelId(result.model_id)

      // 轮询状态
      pollModelingStatus(result.model_id)
      
    } catch (error) {
      console.error('统一建模启动失败:', error)
      setModelingStatus('error')
    }
  }

  // 轮询建模状态
  const pollModelingStatus = async (modelId: string) => {
    const interval = setInterval(async () => {
      try {
        const status = await api.unifiedModeling.getStatus(modelId)
        
        if (status.status === 'completed') {
          setFinalResult(status)
          setModelingStatus('completed')
          setProgress(100)
          clearInterval(interval)
        } else if (status.status === 'failed') {
          setModelingStatus('error')
          clearInterval(interval)
        } else {
          // 模拟进度更新
          setProgress(prev => Math.min(prev + 10, 90))
        }
      } catch (error) {
        console.error('状态查询失败:', error)
        clearInterval(interval)
      }
    }, 3000)
  }

  // 轮询分析状态
  const pollAnalysisStatus = async (taskId: string) => {
    const interval = setInterval(async () => {
      try {
        const taskStatus = await api.unifiedModeling.getAnalysisStatus(taskId)
        
        console.log('分析任务状态:', taskStatus)
        
        if (taskStatus.status === 'completed') {
          setAnalysisResult(taskStatus.result)
          clearInterval(interval)
          console.log('✅ 分析完成，房间数:', taskStatus.result?.room_details?.length || 0)
        } else if (taskStatus.status === 'failed') {
          console.error('❌ 分析失败:', taskStatus.message)
          clearInterval(interval)
        } else {
          // 显示进度信息
          console.log(`🔄 分析进度: ${taskStatus.progress}% - ${taskStatus.message}`)
        }
      } catch (error) {
        console.error('查询分析状态失败:', error)
        clearInterval(interval)
      }
    }, 3000) // 每3秒查询一次
  }

  // 处理文件下载
  const handleDownload = async (fileType: string, taskId: string) => {
    try {
      const blob = await api.unifiedModeling.download(fileType, taskId)
      
      // 创建下载链接
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      
      // 设置文件名
      const fileExtensions: Record<string, string> = {
        'unified_model': '.glb',
        'traditional_model': '.glb',
        'obj_model': '.obj',  // 添加OBJ文件支持
        'web_demo': '.html',
        'amap_integration': '.js',
        'config_file': '.json'
      }
      
      const extension = fileExtensions[fileType] || '.bin'
      link.download = `${fileType}_${taskId}${extension}`
      
      // 触发下载
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
      
    } catch (error) {
      console.error('下载失败:', error)
      alert('下载失败，请稍后重试')
    }
  }

  // 处理文件预览
  const handlePreview = async (fileType: string, taskId: string) => {
    try {
      if (fileType.includes('web')) {
        // 对于web演示，在新窗口打开
        const blob = await api.unifiedModeling.download(fileType, taskId)
        const url = window.URL.createObjectURL(blob)
        window.open(url, '_blank')
      } else {
        // 其他类型暂时不支持预览
        alert('该文件类型暂不支持预览，请下载后使用相应软件打开')
      }
    } catch (error) {
      console.error('预览失败:', error)
      alert('预览失败，请稍后重试')
    }
  }

  const getTechIcon = (techName: string) => {
    switch (techName) {
      case 'hybrid_modeling':
        return <Layers className="w-4 h-4" />
      case 'mcp_ai':
        return <Zap className="w-4 h-4" />
      case 'amap_threejs':
        return <Globe className="w-4 h-4" />
      case 'traditional_fallback':
        return <Cpu className="w-4 h-4" />
      default:
        return <Palette className="w-4 h-4" />
    }
  }

  return (
    <div className="container mx-auto p-6 space-y-6">
      {/* 页面标题 */}
      <div className="text-center space-y-2">
        <h1 className="text-3xl font-bold">统一医院建模系统</h1>
        <p className="text-muted-foreground">
          集成MCP AI、混合建模、传统建模和高德地图+Three.js的一体化解决方案
        </p>
      </div>

      <Tabs defaultValue="overview" className="space-y-6">
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="overview">系统概览</TabsTrigger>
          <TabsTrigger value="upload">上传分析</TabsTrigger>
          <TabsTrigger value="configure">配置建模</TabsTrigger>
          <TabsTrigger value="results">查看结果</TabsTrigger>
        </TabsList>

        {/* 系统概览 */}
        <TabsContent value="overview" className="space-y-6">
          {!strategies ? (
            <Card>
              <CardContent className="text-center py-8">
                <p className="text-muted-foreground">正在加载系统信息...</p>
              </CardContent>
            </Card>
          ) : strategies && (strategies.unified_approach || strategies.integrated_technologies) ? (
            <>
              {/* 统一建模系统介绍 */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <div className="w-8 h-8 rounded-lg bg-gradient-to-r from-blue-500 to-purple-500 flex items-center justify-center">
                      <Layers className="w-4 h-4 text-white" />
                    </div>
                    {strategies.unified_approach?.name || '统一建模系统'} {strategies.unified_approach?.version || 'v1.0'}
                  </CardTitle>
                  <CardDescription>{strategies.unified_approach?.description || '集成多种技术的一体化建模解决方案'}</CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="bg-blue-50 p-4 rounded-lg">
                    <h4 className="font-medium mb-2">设计理念</h4>
                    <p className="text-sm text-muted-foreground">{strategies.unified_approach?.philosophy || '智能融合所有技术优势，提供最优建模方案'}</p>
                  </div>
                </CardContent>
              </Card>

              {/* 集成技术 */}
              <Card>
                <CardHeader>
                  <CardTitle>集成技术组合</CardTitle>
                  <CardDescription>四大核心技术，智能融合，自动选择最优组合</CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
                    {strategies.integrated_technologies?.map((tech) => (
                      <div key={tech.name} className="border rounded-lg p-4 space-y-3">
                        <div className="flex items-center gap-2">
                          {getTechIcon(tech.name)}
                          <h4 className="font-medium text-sm">{tech.display_name}</h4>
                        </div>
                        <Badge variant="outline" className="text-xs">{tech.role}</Badge>
                        <p className="text-xs text-muted-foreground">{tech.description}</p>
                        <div className="flex flex-wrap gap-1">
                          {tech.advantages?.map((advantage) => (
                            <Badge key={advantage} variant="secondary" className="text-xs">{advantage}</Badge>
                          ))}
                        </div>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>

              {/* 处理流水线 */}
              {strategies.processing_pipeline && (
                <Card>
                  <CardHeader>
                    <CardTitle>智能处理流水线</CardTitle>
                    <CardDescription>自动化的五阶段处理流程，确保最优输出质量</CardDescription>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-4">
                      {strategies.processing_pipeline.stages?.map((stage, index) => (
                        <div key={stage.order} className="flex items-center gap-4 p-4 border rounded-lg">
                          <div className="w-10 h-10 rounded-full bg-blue-500 text-white flex items-center justify-center font-medium">
                            {stage.order}
                          </div>
                          <div className="flex-1">
                            <h4 className="font-medium">{stage.name}</h4>
                            <p className="text-sm text-muted-foreground">{stage.output}</p>
                          </div>
                          <div className="text-right">
                            <div className="text-xs text-muted-foreground">
                              {stage.technologies?.join(' + ')}
                            </div>
                          </div>
                          {index < (strategies.processing_pipeline.stages?.length || 0) - 1 && (
                            <div className="w-6 h-px bg-border"></div>
                          )}
                        </div>
                      )) || []}
                    </div>
                  </CardContent>
                </Card>
              )}

              {/* 输出能力和用户收益 */}
              <div className="grid gap-6 md:grid-cols-2">
                {strategies.output_capabilities && (
                  <Card>
                    <CardHeader>
                      <CardTitle>输出能力</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div>
                        <h4 className="font-medium text-sm mb-2">支持格式</h4>
                        <div className="flex flex-wrap gap-2">
                          {strategies.output_capabilities.formats?.map((format) => (
                            <Badge key={format} variant="secondary">{format}</Badge>
                          )) || []}
                        </div>
                      </div>
                      <div>
                        <h4 className="font-medium text-sm mb-2">质量级别</h4>
                        <div className="flex flex-wrap gap-2">
                          {strategies.output_capabilities.quality_levels?.map((level) => (
                            <Badge key={level} variant="secondary">{level}</Badge>
                          )) || []}
                        </div>
                      </div>
                      <div>
                        <h4 className="font-medium text-sm mb-2">平台支持</h4>
                        <div className="flex flex-wrap gap-2">
                          {strategies.output_capabilities.platform_support?.map((platform) => (
                            <Badge key={platform} variant="outline">{platform}</Badge>
                          )) || []}
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                )}

                {strategies.user_benefits && (
                  <Card>
                    <CardHeader>
                      <CardTitle>用户收益</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-3">
                      {Object.entries(strategies.user_benefits).map(([key, value]) => (
                        <div key={key} className="space-y-1">
                          <h4 className="font-medium text-sm">{
                            key === 'no_technical_decisions' ? '无需技术决策' :
                            key === 'guaranteed_quality' ? '质量保证' :
                            key === 'comprehensive_output' ? '全面输出' :
                            '未来适配'
                          }</h4>
                          <p className="text-xs text-muted-foreground">{value}</p>
                        </div>
                      ))}
                    </CardContent>
                  </Card>
                )}
              </div>
            </>
          ) : (
            <Card>
              <CardContent className="text-center py-8">
                <p className="text-muted-foreground">系统信息加载失败，请刷新页面重试</p>
              </CardContent>
            </Card>
          )}
        </TabsContent>

        {/* 上传分析 */}
        <TabsContent value="upload" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>上传平面图</CardTitle>
              <CardDescription>支持JPG、PNG格式的医院平面图</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center">
                <input
                  type="file"
                  accept="image/*"
                  onChange={(e) => e.target.files && setSelectedFile(e.target.files[0])}
                  className="hidden"
                  id="file-upload"
                />
                <label htmlFor="file-upload" className="cursor-pointer">
                  <Upload className="w-12 h-12 mx-auto mb-4 text-gray-400" />
                  <p className="text-lg mb-2">点击上传平面图</p>
                  <p className="text-sm text-muted-foreground">
                    {selectedFile ? selectedFile.name : '拖拽文件到此处或点击选择'}
                  </p>
                </label>
              </div>
              
              {selectedFile && (
                <Button onClick={handleFileUpload} className="w-full">
                  <Upload className="w-4 h-4 mr-2" />
                  开始上传和分析
                </Button>
              )}
            </CardContent>
          </Card>

          {/* 分析结果 */}
          {analysisResult && (
            <Card>
              <CardHeader>
                <CardTitle>智能分析结果</CardTitle>
                <CardDescription>系统已分析您的平面图，推荐以下技术组合</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="grid gap-4 md:grid-cols-2">
                  <div>
                    <h4 className="font-medium mb-2">图像特征分析</h4>
                    <div className="space-y-2 text-sm">
                      <div className="flex justify-between">
                        <span>复杂度：</span>
                        <span>{analysisResult.image_analysis?.complexity_level || '中等'}</span>
                      </div>
                      <div className="flex justify-between">
                        <span>房间数量：</span>
                        <span>{analysisResult.image_analysis?.room_count || 0}</span>
                      </div>
                      <div className="flex justify-between">
                        <span>图像质量：</span>
                        <span>{((analysisResult.image_analysis?.quality_score || 0.8) * 100).toFixed(0)}%</span>
                      </div>
                    </div>
                  </div>
                  <div>
                    <h4 className="font-medium mb-2">推荐技术组合</h4>
                    <div className="space-y-2">
                      {analysisResult.technologies_to_combine?.map((tech: string) => (
                        <Badge key={tech} variant="outline">{tech}</Badge>
                      ))}
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          )}
        </TabsContent>

        {/* 配置建模 */}
        <TabsContent value="configure" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>建模偏好设置</CardTitle>
              <CardDescription>调整建模参数，系统将自动优化技术组合</CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="space-y-4">
                <div>
                  <label className="text-sm font-medium mb-2 block">
                    质量优先级: {qualityPriority[0]}%
                  </label>
                  <Slider
                    value={qualityPriority}
                    onValueChange={setQualityPriority}
                    max={100}
                    step={5}
                    className="w-full"
                  />
                  <p className="text-xs text-muted-foreground mt-1">
                    高质量会启用更多AI增强和细节优化
                  </p>
                </div>

                <div>
                  <label className="text-sm font-medium mb-2 block">
                    速度优先级: {speedPriority[0]}%
                  </label>
                  <Slider
                    value={speedPriority}
                    onValueChange={setSpeedPriority}
                    max={100}
                    step={5}
                    className="w-full"
                  />
                  <p className="text-xs text-muted-foreground mt-1">
                    高速度会优先使用快速建模方法
                  </p>
                </div>

                <div className="grid gap-4 md:grid-cols-2">
                  <div className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      id="web-compatibility"
                      checked={webCompatibility}
                      onChange={(e) => setWebCompatibility(e.target.checked)}
                    />
                    <label htmlFor="web-compatibility" className="text-sm font-medium">
                      Web兼容性优化
                    </label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      id="professional-grade"
                      checked={professionalGrade}
                      onChange={(e) => setProfessionalGrade(e.target.checked)}
                    />
                    <label htmlFor="professional-grade" className="text-sm font-medium">
                      专业级输出
                    </label>
                  </div>
                </div>
              </div>

              {uploadedFileId && (
                <Button 
                  onClick={startUnifiedModeling} 
                  className="w-full"
                  disabled={modelingStatus === 'processing'}
                >
                  {modelingStatus === 'processing' ? (
                    <>
                      <Clock className="w-4 h-4 mr-2 animate-spin" />
                      统一建模进行中...
                    </>
                  ) : (
                    <>
                      <PlayCircle className="w-4 h-4 mr-2" />
                      开始统一建模
                    </>
                  )}
                </Button>
              )}
            </CardContent>
          </Card>

          {/* 建模进度 */}
          {modelingStatus === 'processing' && (
            <Card>
              <CardHeader>
                <CardTitle>建模进度</CardTitle>
                <CardDescription>正在执行统一建模流水线...</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <Progress value={progress} className="w-full" />
                  <p className="text-sm text-center text-muted-foreground">
                    {progress < 20 ? '预处理中...' :
                     progress < 40 ? '基础建模中...' :
                     progress < 60 ? 'AI增强中...' :
                     progress < 80 ? '地图集成中...' :
                     progress < 95 ? '优化输出中...' : '即将完成...'}
                  </p>
                </div>
              </CardContent>
            </Card>
          )}
        </TabsContent>

        {/* 查看结果 */}
        <TabsContent value="results" className="space-y-6">
          {finalResult && (
            <>
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <CheckCircle className="w-5 h-5 text-green-500" />
                    统一建模完成
                  </CardTitle>
                  <CardDescription>{finalResult.message}</CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="grid gap-4 md:grid-cols-2">
                    {/* 技术使用情况 */}
                    <div>
                      <h4 className="font-medium mb-3">技术集成详情</h4>
                      <div className="space-y-2">
                        {finalResult.technologies_used?.map((tech: any) => (
                          <div key={tech.name} className="flex items-center justify-between p-2 border rounded">
                            <span className="text-sm">{tech.name}</span>
                            <Badge variant={tech.status === 'completed' ? 'default' : 'secondary'}>
                              {tech.status}
                            </Badge>
                          </div>
                        ))}
                      </div>
                    </div>

                    {/* 质量指标 */}
                    <div>
                      <h4 className="font-medium mb-3">质量指标</h4>
                      <div className="space-y-2">
                        {Object.entries(finalResult.quality_metrics || {}).map(([key, value]) => (
                          <div key={key} className="flex justify-between text-sm">
                            <span className="capitalize">{key.replace('_', ' ')}:</span>
                            <span className="font-medium">{value as string}</span>
                          </div>
                        ))}
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* 下载和预览 */}
              <Card>
                <CardHeader>
                  <CardTitle>输出文件</CardTitle>
                  <CardDescription>多种格式，满足不同使用场景</CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                    {Object.entries(finalResult.outputs || {}).map(([key, url]) => (
                      <div key={key} className="border rounded-lg p-4 space-y-2">
                        <h4 className="font-medium text-sm capitalize">
                          {key.replace('_', ' ')}
                        </h4>
                        <div className="flex gap-2">
                          <Button 
                            size="sm" 
                            variant="outline"
                            onClick={() => handleDownload(key, finalResult.model_id)}
                          >
                            <Download className="w-4 h-4 mr-1" />
                            下载
                          </Button>
                          {key.includes('web') && (
                            <Button 
                              size="sm" 
                              variant="outline"
                              onClick={() => handlePreview(key, finalResult.model_id)}
                            >
                              <Eye className="w-4 h-4 mr-1" />
                              预览
                            </Button>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>

              {/* 使用建议 */}
              <Card>
                <CardHeader>
                  <CardTitle>使用建议</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    <div>
                      <h4 className="font-medium mb-2">适用场景</h4>
                      <div className="flex flex-wrap gap-2">
                        {finalResult.usage_recommendations?.best_for?.map((use: string) => (
                          <Badge key={use} variant="outline">{use}</Badge>
                        ))}
                      </div>
                    </div>
                    <div>
                      <h4 className="font-medium mb-2">推荐下载</h4>
                      <p className="text-sm text-muted-foreground">
                        {finalResult.usage_recommendations?.download_priority}
                      </p>
                    </div>
                    <div>
                      <h4 className="font-medium mb-2">Web集成</h4>
                      <p className="text-sm text-muted-foreground">
                        {finalResult.usage_recommendations?.web_integration}
                      </p>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </>
          )}

          {modelingStatus === 'idle' && (
            <Card>
              <CardContent className="text-center py-8">
                <p className="text-muted-foreground">
                  请先上传平面图并配置建模参数，然后开始统一建模
                </p>
              </CardContent>
            </Card>
          )}
        </TabsContent>
      </Tabs>
    </div>
  )
}

export default UnifiedModelingPage